package com.jdk.demo.fileChannel.read;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Test2_4 {
	
	private static FileInputStream fisRef;
	private static FileChannel fileChannel;

	// 验证read方法具有同步性
	public static void main(String[] args) throws Exception {
		fisRef = new FileInputStream("b1.txt");
		fileChannel = fisRef.getChannel();
		
		// 一共输出27个字符串，虽然输出的顺序是乱序的，但每组的序号都包含1-9，并没有出现重复的字符串，说明read方法是同步的
		for (int i = 0; i < 1; i++) {
			Thread thread1 = new Thread(){
				@Override
				public void run(){
					try{
						ByteBuffer bytebuffer = ByteBuffer.allocate(5);
						int readLength = fileChannel.read(bytebuffer);
						while(readLength != -1){
							byte[] getByte = bytebuffer.array();
							System.out.println(new String(getByte, 0, readLength));
							bytebuffer.clear();
							readLength = fileChannel.read(bytebuffer);
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			};
			Thread thread2 = new Thread(){
				@Override
				public void run(){
					try{
						ByteBuffer bytebuffer = ByteBuffer.allocate(5);
						int readLength = fileChannel.read(bytebuffer);
						while(readLength != -1){
							byte[] getByte = bytebuffer.array();
							System.out.println(new String(getByte, 0, readLength));
							bytebuffer.clear();
							readLength = fileChannel.read(bytebuffer);
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			};
			thread1.start();
			thread2.start();
		}
		
		Thread.sleep(3000);
		fileChannel.close();
		fisRef.close();
	}
	
}
